package yams.resource.impl;

import com.google.common.collect.Lists;
import javafx.util.Callback;
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import yams.common.constants.CouponStatusEnum;
import yams.domain.*;
import yams.resource.ICouponResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.response.Response;
import yams.service.ICommonService;
import yams.service.ICouponService;
import yams.service.impl.DefaultCommonService;
import yams.utils.SystemTool;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 券服务
 * Created by Luffy on 2017/06/22.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/coupon")
public class DefaultCouponResource extends JsonCommonResource implements ICouponResource {

    @Resource
    private ICouponService couponService;

    private ICommonService couponModelService;
    private ICommonService userService;

    @Resource
    private MySQLMaxValueIncrementer mySequence;

    private static final int USER_GT_COUPON = 1;
    private static final int USER_EQ_COUPON = 0;
    private static final int USER_LE_COUPON = -1;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<CouponEntity> page(@RequestBody CouponEntity couponEntity) {
        return _pageAll(couponService, couponEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<CouponEntity> findById(@PathVariable String id) {
        return _findOne(couponService, id, 0, new Callback<CouponEntity, Object>() {
            @Override
            public Object call(CouponEntity param) {
                if (param != null) {
//                    BillEntity billEntity = new BillEntity();
//                    billEntity.getProperties().put("status", 0);
//                    billEntity.getProperties().put("user_id_obj_ae", param.getId());
//                    List<BillEntity> l = billService.listAll(billEntity);
//                    if (l != null && l.size() > 0) {
//                        BigDecimal total = new BigDecimal(0);
//                        for (BillEntity entity : l) {
//                            total = total.add(entity.getActualAmount());
//                        }
//                        param.setToPayAmount(total);
//                    }
                }
                return null;
            }
        });
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<CouponEntity> findByCode(@PathVariable String code) {
        return _findOne(couponService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<CouponEntity> save(@RequestBody CouponEntity couponEntity) {
        return _saveInfo(couponService, couponEntity);
    }

    /**
     * 生成券
     * @param couponEntity 包含券模型和数量
     * @return
     */
    @RequestMapping(value = "/generateCoupons", method = RequestMethod.PUT)
    public Response generateCouponsSave(@RequestBody CouponEntity couponEntity) {

        Map<String,Object> map = couponEntity.getProperties();

            String couponModelId = map.get("id").toString();
            Integer couponCnt = Integer.valueOf(map.get("couponCnt").toString());
            for(int i = 0 ; i < couponCnt ; i++){
                CouponEntity entity = new CouponEntity();
                entity.setCode(String.valueOf(System.nanoTime()));
                CouponModelEntity couponModelEntity = (CouponModelEntity)couponModelService.findById(couponModelId);
                entity.setCouponModel(couponModelEntity);
                entity.setName(couponModelEntity.getName()+ i);
                couponService.saveInfo(entity , (Callback<CouponEntity, Object>) param -> {
                    if (StringUtils.isEmpty(param.getId())) {
                        param.setId(SystemTool.uuid());
                        param.setCreatedDate(new Date());
                    }
                    param.setModifiedDate(new Date());
                    return null;
                });
            }

        return JsonResponse.OK();
    }

    /**
     * 发放券前的检查
     * @param couponEntity
     * @return
     */
    @RequestMapping(value = "/diliveryCheck", method = RequestMethod.POST)
    public Response diliveryCheck(@RequestBody CouponEntity couponEntity) {

        JsonResponse rep = JsonResponse.OK();
        //所有会员
        JsonResponse<UserEntity> r = _pageAll(userService, new UserEntity());
        Long userTotal = r.getTotal();
        //可用券
        Long couponTotal = couponService.count(couponEntity);

        EmptyEntity emptyEntity = new EmptyEntity();
        emptyEntity.getProperties().put("userTotal",userTotal);
        emptyEntity.getProperties().put("couponTotal",couponTotal);

        return JsonResponse.buildSingle(emptyEntity);
    }

    /**
     * 发放券
     * @param couponEntity
     * @return
     */
    @RequestMapping(value = "/diliveryCoupons", method = RequestMethod.POST)
    public Response diliveryCoupons(@RequestBody CouponEntity couponEntity) {

        //所有会员
        JsonResponse<UserEntity> r = _pageAll(userService, new UserEntity());
        List<UserEntity> userList = (List<UserEntity>)r.getRows();
        //可用券
        List<CouponEntity> couponList = couponService.listAll(couponEntity);

        String msg = "";
        //发放券，券的状态需要改变，券的user_id字段也需要更新
        if(!CollectionUtils.isEmpty(userList) && !CollectionUtils.isEmpty(couponList)){
            Integer min = 0;
            Integer max = 0;
            Integer flag = 0;
            if(userList.size() > couponList.size()){
                 min = couponList.size();
                 max = userList.size();
                 flag = 1;
            }else if(userList.size() == couponList.size()){
                 min = couponList.size();
                 max = userList.size();
            }else{
                 min = userList.size();
                 max = couponList.size();
                 flag = -1;
            }

            for(int i = 0 ; i < min ; i++){

                CouponEntity coupon = couponList.get(i);
                UserEntity user = userList.get(i);

                coupon.setUser(user);
                coupon.setStatus(CouponStatusEnum.OBTAIN.getValue());
                couponService.saveInfo(coupon);

            }

            if(flag == USER_GT_COUPON){
                 msg = "券全部发完，还有"+(max-min)+"会员没有得到券";
            }else if(flag == USER_EQ_COUPON){
                 msg = "券全部发完，所有会员都得到了券";
            }else{
                 msg = "全部会员都拿到券，还余留"+(max-min)+"券";
            }

        }

        //券全部发放完毕
        EmptyEntity emptyEntity = new EmptyEntity();
        emptyEntity.getProperties().put("msg",msg);

        return JsonResponse.buildSingle(emptyEntity);
    }

    /**
     * 对某个会员发放某张券
     * @param couponEntity
     * @return
     */
    @RequestMapping(value = "/diliveryCoupon", method = RequestMethod.POST)
    public Response diliveryCoupon(@RequestBody CouponEntity couponEntity) {

        Map<String,Object> map = couponEntity.getProperties();
        String userId = map.get("userId").toString();
        String couponId = map.get("couponId").toString();

        UserEntity user = (UserEntity) _findOne(userService, userId, 0).getValue();
        CouponEntity coupon = (CouponEntity) _findOne(couponService, couponId, 0).getValue();

        coupon.setUser(user);
        coupon.setStatus(CouponStatusEnum.OBTAIN.getValue());
        couponService.saveInfo(coupon);

        return JsonResponse.OK();
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<CouponEntity> delete(@PathVariable String id) {
        return _delete(couponService, id);
    }


    @RequestMapping(value = "/queryCouponByUser/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<CouponEntity> queryCouponByUser(@PathVariable String id) {

        UserEntity userEntity = (UserEntity) userService.findById(id);
        List<CouponEntity> resultList = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(userEntity.getCoupons())){
            resultList = userEntity.getCoupons().stream().filter( coupon -> {
                return Objects.equals(coupon.getStatus(),2) ? true : false;
            }).collect(Collectors.toList());
        }
        return JsonResponse.build(resultList);

    }



    @Override
    public void initService() {

        if (couponModelService == null)
            couponModelService = new DefaultCommonService("couponModelRepository");
        if (userService == null)
            userService = new DefaultCommonService("userRepository");

    }

   /* @RequestMapping(value = "/bind", method = RequestMethod.POST)
    @Override
    public JsonResponse<CouponModelEntity> bindUser(@RequestBody CouponModelEntity couponModelEntity) {
        if (StringUtils.hasText(couponModelEntity.getPhone())) {
            CouponModelEntity old = ((IUserRepository) ((IRepository) couponService.getRepository())).findByPhone(couponModelEntity.getPhone());
            if (old == null) {
                return JsonResponse.ERROR("绑定的手机号未注册，请注册");
            }
            old.setWeChat(couponModelEntity.getWeChat());
            old.setFollowDate(new Date());
            couponService.saveInfo(old);
        }
        return JsonResponse.ERROR("手机号为空，请填写");
    }*/
}
